<template>
  <div class="collaborative-editor">
    <!-- 协作状态栏 -->
    <div class="collab-statusbar">
      <div class="statusbar-left">
        <el-icon class="sync-icon" :class="{ syncing: isSyncing }"><Connection /></el-icon>
        <span class="sync-status">{{ syncStatus }}</span>
        <el-tag v-if="isOnline" type="success" size="small" effect="plain">已连接</el-tag>
        <el-tag v-else type="danger" size="small" effect="plain">已断开</el-tag>
      </div>

      <div class="statusbar-center">
        <div class="collaborators">
          <el-tooltip 
            v-for="user in onlineUsers" 
            :key="user.id"
            :content="`${user.name}${user.isEditing ? ' (正在编辑)' : ''}`"
            placement="bottom"
          >
            <el-avatar 
              :size="28" 
              :style="{ 
                background: user.color,
                border: user.isEditing ? '2px solid #409eff' : 'none'
              }"
            >
              {{ user.name.charAt(0) }}
            </el-avatar>
          </el-tooltip>

          <el-popover placement="bottom" :width="300" trigger="click">
            <template #reference>
              <el-avatar :size="28" class="more-users">
                +{{ onlineUsers.length }}
              </el-avatar>
            </template>
            <div class="user-list">
              <h4>在线用户 ({{ onlineUsers.length }})</h4>
              <div 
                v-for="user in onlineUsers" 
                :key="user.id"
                class="user-item"
              >
                <el-avatar :size="32" :style="{ background: user.color }">
                  {{ user.name.charAt(0) }}
                </el-avatar>
                <div class="user-info">
                  <div class="user-name">{{ user.name }}</div>
                  <div class="user-status">
                    <el-icon v-if="user.isEditing"><Edit /></el-icon>
                    {{ user.isEditing ? '正在编辑' : '在线' }}
                  </div>
                </div>
                <el-tag :type="user.isEditing ? 'primary' : 'info'" size="small" effect="plain">
                  {{ user.role }}
                </el-tag>
              </div>
            </div>
          </el-popover>
        </div>
      </div>

      <div class="statusbar-right">
        <el-button size="small" text @click="showCollabSettings = true">
          <el-icon><Setting /></el-icon>
          协作设置
        </el-button>
        <el-button size="small" text @click="showChatPanel = !showChatPanel">
          <el-icon><ChatDotSquare /></el-icon>
          聊天
          <el-badge v-if="unreadMessages > 0" :value="unreadMessages" class="badge" />
        </el-button>
      </div>
    </div>

    <!-- 主编辑区域 -->
    <div class="collab-main">
      <slot></slot>

      <!-- 光标指示器 -->
      <div 
        v-for="cursor in remoteCursors" 
        :key="cursor.userId"
        class="remote-cursor"
        :style="{
          left: cursor.x + 'px',
          top: cursor.y + 'px'
        }"
      >
        <div class="cursor-pointer" :style="{ background: cursor.color }"></div>
        <div class="cursor-label" :style="{ background: cursor.color }">
          {{ cursor.userName }}
        </div>
      </div>

      <!-- 选区指示器 -->
      <div 
        v-for="selection in remoteSelections" 
        :key="selection.userId"
        class="remote-selection"
        :style="{
          left: selection.x + 'px',
          top: selection.y + 'px',
          width: selection.width + 'px',
          height: selection.height + 'px',
          background: selection.color + '33'
        }"
      ></div>
    </div>

    <!-- 聊天面板 -->
    <transition name="slide-left">
      <div v-if="showChatPanel" class="chat-panel">
        <div class="chat-header">
          <h4>
            <el-icon><ChatDotSquare /></el-icon>
            团队聊天
          </h4>
          <el-button size="small" text @click="showChatPanel = false">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>

        <div class="chat-messages">
          <div 
            v-for="msg in chatMessages" 
            :key="msg.id"
            class="chat-message"
            :class="{ self: msg.userId === currentUserId }"
          >
            <el-avatar :size="32" :style="{ background: msg.userColor }">
              {{ msg.userName.charAt(0) }}
            </el-avatar>
            <div class="chat-content">
              <div class="chat-meta">
                <span class="chat-user">{{ msg.userName }}</span>
                <span class="chat-time">{{ formatTime(msg.timestamp) }}</span>
              </div>
              <div class="chat-text">{{ msg.content }}</div>
            </div>
          </div>
        </div>

        <div class="chat-input">
          <el-input 
            v-model="chatInput" 
            placeholder="输入消息..."
            @keydown.enter="sendChatMessage"
          >
            <template #append>
              <el-button @click="sendChatMessage">
                <el-icon><Promotion /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
    </transition>

    <!-- 变更历史侧边栏 -->
    <transition name="slide-right">
      <div v-if="showChanges" class="changes-panel">
        <div class="changes-header">
          <h4>
            <el-icon><Clock /></el-icon>
            实时变更
          </h4>
          <el-button size="small" text @click="showChanges = false">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>

        <div class="changes-list">
          <div 
            v-for="change in recentChanges" 
            :key="change.id"
            class="change-item"
          >
            <el-avatar :size="24" :style="{ background: change.userColor }">
              {{ change.userName.charAt(0) }}
            </el-avatar>
            <div class="change-content">
              <div class="change-description">
                <strong>{{ change.userName }}</strong> {{ change.description }}
              </div>
              <div class="change-time">{{ formatTime(change.timestamp) }}</div>
            </div>
          </div>
        </div>
      </div>
    </transition>

    <!-- 协作设置对话框 -->
    <el-dialog
      v-model="showCollabSettings"
      title="协作设置"
      width="500px"
    >
      <el-form label-width="120px">
        <el-form-item label="显示光标">
          <el-switch v-model="collabSettings.showCursors" />
        </el-form-item>
        <el-form-item label="显示选区">
          <el-switch v-model="collabSettings.showSelections" />
        </el-form-item>
        <el-form-item label="自动同步">
          <el-switch v-model="collabSettings.autoSync" />
        </el-form-item>
        <el-form-item label="同步间隔">
          <el-slider v-model="collabSettings.syncInterval" :min="1" :max="10" :step="1" />
          <div class="slider-tips">
            <span>{{ collabSettings.syncInterval }}秒</span>
          </div>
        </el-form-item>
        <el-form-item label="显示变更提示">
          <el-switch v-model="collabSettings.showChangeNotifications" />
        </el-form-item>
        <el-form-item label="冲突解决策略">
          <el-select v-model="collabSettings.conflictStrategy">
            <el-option label="最后写入优先" value="last-write-wins" />
            <el-option label="手动合并" value="manual" />
            <el-option label="自动合并" value="auto-merge" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCollabSettings = false">取消</el-button>
        <el-button type="primary" @click="saveCollabSettings">保存</el-button>
      </template>
    </el-dialog>

    <!-- 冲突解决对话框 -->
    <el-dialog
      v-model="showConflictDialog"
      title="检测到冲突"
      width="700px"
    >
      <el-alert 
        title="同时编辑了相同内容" 
        type="warning" 
        :closable="false"
        style="margin-bottom: 20px"
      >
        你和 <strong>{{ conflictInfo.userName }}</strong> 同时修改了相同的内容，请选择如何解决。
      </el-alert>

      <el-row :gutter="20">
        <el-col :span="12">
          <h4>你的版本</h4>
          <div class="conflict-version">
            <pre>{{ conflictInfo.yourVersion }}</pre>
          </div>
          <el-button type="primary" @click="resolveConflict('yours')">使用我的版本</el-button>
        </el-col>
        <el-col :span="12">
          <h4>{{ conflictInfo.userName }} 的版本</h4>
          <div class="conflict-version">
            <pre>{{ conflictInfo.theirVersion }}</pre>
          </div>
          <el-button type="primary" @click="resolveConflict('theirs')">使用对方版本</el-button>
        </el-col>
      </el-row>

      <el-divider />

      <div>
        <h4>手动合并</h4>
        <el-input 
          v-model="conflictInfo.mergedVersion" 
          type="textarea"
          :rows="6"
          placeholder="手动编辑合并后的内容"
        />
      </div>

      <template #footer>
        <el-button @click="showConflictDialog = false">取消</el-button>
        <el-button type="primary" @click="resolveConflict('merged')">使用合并版本</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Connection, Setting, ChatDotSquare, Edit, Clock, Close,
  Promotion
} from '@element-plus/icons-vue'

const props = defineProps({
  documentId: {
    type: String,
    required: true
  },
  currentUser: {
    type: Object,
    default: () => ({
      id: 'user-1',
      name: '当前用户',
      color: '#409eff',
      role: '编辑者'
    })
  }
})

const emit = defineEmits(['change', 'sync', 'conflict'])

// 状态
const isOnline = ref(true)
const isSyncing = ref(false)
const syncStatus = ref('已同步')
const showChatPanel = ref(false)
const showChanges = ref(false)
const showCollabSettings = ref(false)
const showConflictDialog = ref(false)
const unreadMessages = ref(0)
const currentUserId = computed(() => props.currentUser.id)

// 在线用户（模拟数据）
const onlineUsers = ref([
  {
    id: 'user-1',
    name: '张三',
    color: '#409eff',
    role: '管理员',
    isEditing: true
  },
  {
    id: 'user-2',
    name: '李四',
    color: '#67c23a',
    role: '编辑者',
    isEditing: false
  },
  {
    id: 'user-3',
    name: '王五',
    color: '#e6a23c',
    role: '查看者',
    isEditing: false
  }
])

// 远程光标
const remoteCursors = ref([
  {
    userId: 'user-2',
    userName: '李四',
    color: '#67c23a',
    x: 100,
    y: 200
  }
])

// 远程选区
const remoteSelections = ref([])

// 聊天消息
const chatMessages = ref([
  {
    id: '1',
    userId: 'user-2',
    userName: '李四',
    userColor: '#67c23a',
    content: '大家好，我正在修改表单配置',
    timestamp: Date.now() - 300000
  },
  {
    id: '2',
    userId: 'user-1',
    userName: '张三',
    userColor: '#409eff',
    content: '好的，我在优化页面布局',
    timestamp: Date.now() - 120000
  }
])

const chatInput = ref('')

// 最近变更
const recentChanges = ref([
  {
    id: '1',
    userId: 'user-2',
    userName: '李四',
    userColor: '#67c23a',
    description: '添加了用户名字段',
    timestamp: Date.now() - 60000
  },
  {
    id: '2',
    userId: 'user-3',
    userName: '王五',
    userColor: '#e6a23c',
    description: '修改了表单标题',
    timestamp: Date.now() - 120000
  }
])

// 协作设置
const collabSettings = reactive({
  showCursors: true,
  showSelections: true,
  autoSync: true,
  syncInterval: 3,
  showChangeNotifications: true,
  conflictStrategy: 'last-write-wins'
})

// 冲突信息
const conflictInfo = reactive({
  userName: '李四',
  yourVersion: '',
  theirVersion: '',
  mergedVersion: ''
})

// WebSocket连接（模拟）
let ws = null

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 连接协作服务器
const connect = () => {
  // 模拟WebSocket连接
  console.log('连接到协作服务器...', props.documentId)
  isOnline.value = true
  syncStatus.value = '已同步'
  
  // 模拟接收消息
  setInterval(() => {
    // 模拟其他用户的光标移动
    if (remoteCursors.value.length > 0) {
      remoteCursors.value[0].x = Math.random() * 300 + 100
      remoteCursors.value[0].y = Math.random() * 300 + 100
    }
  }, 2000)
}

// 断开连接
const disconnect = () => {
  console.log('断开协作服务器连接')
  isOnline.value = false
  syncStatus.value = '未连接'
}

// 发送变更
const sendChange = (change) => {
  if (!isOnline.value) {
    ElMessage.warning('未连接到服务器')
    return
  }
  
  isSyncing.value = true
  syncStatus.value = '同步中...'
  
  setTimeout(() => {
    isSyncing.value = false
    syncStatus.value = '已同步'
    emit('change', change)
  }, 500)
}

// 发送聊天消息
const sendChatMessage = () => {
  if (!chatInput.value.trim()) return
  
  const message = {
    id: Date.now().toString(),
    userId: currentUserId.value,
    userName: props.currentUser.name,
    userColor: props.currentUser.color,
    content: chatInput.value,
    timestamp: Date.now()
  }
  
  chatMessages.value.push(message)
  chatInput.value = ''
  
  // 滚动到底部
  setTimeout(() => {
    const chatMessagesEl = document.querySelector('.chat-messages')
    if (chatMessagesEl) {
      chatMessagesEl.scrollTop = chatMessagesEl.scrollHeight
    }
  }, 100)
}

// 保存协作设置
const saveCollabSettings = () => {
  showCollabSettings.value = false
  ElMessage.success('设置已保存')
}

// 解决冲突
const resolveConflict = (strategy) => {
  let resolvedVersion = ''
  
  if (strategy === 'yours') {
    resolvedVersion = conflictInfo.yourVersion
  } else if (strategy === 'theirs') {
    resolvedVersion = conflictInfo.theirVersion
  } else {
    resolvedVersion = conflictInfo.mergedVersion
  }
  
  emit('conflict', { strategy, resolvedVersion })
  showConflictDialog.value = false
  ElMessage.success('冲突已解决')
}

// 生命周期
onMounted(() => {
  connect()
})

onBeforeUnmount(() => {
  disconnect()
})

// 暴露方法
defineExpose({
  sendChange,
  connect,
  disconnect
})
</script>

<style scoped>
.collaborative-editor {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 状态栏 */
.collab-statusbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
}

.statusbar-left,
.statusbar-center,
.statusbar-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.sync-icon {
  font-size: 18px;
  color: #67c23a;
  transition: all 0.3s;
}

.sync-icon.syncing {
  color: #409eff;
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.sync-status {
  font-size: 14px;
  color: #606266;
}

/* 协作者列表 */
.collaborators {
  display: flex;
  align-items: center;
  gap: -8px;
}

.collaborators .el-avatar {
  border: 2px solid white;
  cursor: pointer;
  transition: all 0.3s;
}

.collaborators .el-avatar:hover {
  transform: translateY(-2px);
  z-index: 10;
}

.more-users {
  background: #909399;
  cursor: pointer;
}

.user-list {
  max-height: 400px;
  overflow-y: auto;
}

.user-list h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 10px;
  border-radius: 6px;
  margin-bottom: 8px;
  transition: all 0.3s;
}

.user-item:hover {
  background: #f5f7fa;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 2px;
}

.user-status {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 主编辑区 */
.collab-main {
  flex: 1;
  position: relative;
  overflow: hidden;
}

/* 远程光标 */
.remote-cursor {
  position: absolute;
  pointer-events: none;
  z-index: 1000;
  transition: all 0.1s;
}

.cursor-pointer {
  width: 2px;
  height: 20px;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0.3; }
}

.cursor-label {
  position: absolute;
  top: -22px;
  left: 4px;
  padding: 2px 6px;
  border-radius: 4px;
  color: white;
  font-size: 12px;
  white-space: nowrap;
}

/* 远程选区 */
.remote-selection {
  position: absolute;
  pointer-events: none;
  z-index: 999;
  border: 1px solid;
  transition: all 0.1s;
}

/* 聊天面板 */
.chat-panel {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 320px;
  background: white;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  z-index: 100;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.chat-header h4 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #303133;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.chat-message {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.chat-message.self {
  flex-direction: row-reverse;
}

.chat-content {
  flex: 1;
  min-width: 0;
}

.chat-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 12px;
}

.chat-user {
  color: #303133;
  font-weight: 600;
}

.chat-time {
  color: #c0c4cc;
}

.chat-text {
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 8px;
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
}

.chat-message.self .chat-text {
  background: #ecf5ff;
}

.chat-input {
  padding: 15px;
  border-top: 1px solid #e4e7ed;
}

/* 变更面板 */
.changes-panel {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 300px;
  background: white;
  border-left: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  z-index: 100;
}

.changes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.changes-header h4 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #303133;
}

.changes-list {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.change-item {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.change-content {
  flex: 1;
}

.change-description {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.change-time {
  font-size: 12px;
  color: #c0c4cc;
}

/* 冲突版本 */
.conflict-version {
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
  margin-bottom: 15px;
  max-height: 200px;
  overflow-y: auto;
}

.conflict-version pre {
  margin: 0;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 13px;
  line-height: 1.6;
}

/* 滑动动画 */
.slide-left-enter-active,
.slide-left-leave-active,
.slide-right-enter-active,
.slide-right-leave-active {
  transition: all 0.3s;
}

.slide-left-enter-from,
.slide-right-enter-from {
  transform: translateX(100%);
}

.slide-left-leave-to,
.slide-right-leave-to {
  transform: translateX(100%);
}

/* 滚动条 */
.chat-messages::-webkit-scrollbar,
.changes-list::-webkit-scrollbar,
.user-list::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb,
.changes-list::-webkit-scrollbar-thumb,
.user-list::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}
</style>

